/**
 * Token刷新API路由
 */
import { NextRequest, NextResponse } from 'next/server';
import { AuthService } from '@/lib/auth';

export async function POST(request: NextRequest) {
  try {
    // 从cookie或请求体中获取refresh token
    const refreshTokenFromCookie = request.cookies.get('refresh-token')?.value;
    
    let refreshToken = refreshTokenFromCookie;
    
    // 如果cookie中没有，尝试从请求体获取
    if (!refreshToken) {
      try {
        const body = await request.json();
        refreshToken = body.refreshToken;
      } catch {
        // 忽略JSON解析错误
      }
    }
    
    if (!refreshToken) {
      return NextResponse.json(
        { error: '未找到刷新token', code: 'NO_REFRESH_TOKEN' },
        { status: 400 }
      );
    }

    // 执行token刷新
    const result = await AuthService.refreshToken(refreshToken);

    if (!result.success) {
      // 如果刷新失败，清除cookie
      const response = NextResponse.json(
        { error: result.message, code: 'REFRESH_FAILED' },
        { status: 401 }
      );

      response.cookies.set('auth-token', '', {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 0
      });

      response.cookies.set('refresh-token', '', {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 0
      });

      return response;
    }

    // 设置新的认证cookie
    const response = NextResponse.json({
      message: result.message,
      token: result.token
    });

    if (result.token && result.refreshToken) {
      response.cookies.set('auth-token', result.token, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 7 * 24 * 60 * 60 // 7天
      });

      response.cookies.set('refresh-token', result.refreshToken, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 30 * 24 * 60 * 60 // 30天
      });
    }

    return response;
  } catch (error) {
    console.error('Token刷新API错误:', error);
    return NextResponse.json(
      { error: '服务器内部错误', code: 'INTERNAL_ERROR' },
      { status: 500 }
    );
  }
}

// 不允许其他HTTP方法
export async function GET() {
  return NextResponse.json(
    { error: '方法不允许', code: 'METHOD_NOT_ALLOWED' },
    { status: 405 }
  );
}